<template>
  <div>
    <el-row>
      <el-col :span="12">
        <el-alert
          :title="warning_title"
          type="warning"
          show-icon
          :closable="false"
        ></el-alert>
      </el-col>
      <el-col :span="12" style="padding-left: 30px; padding-top: 2px">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="() => handleAdd()"
          >新增进度</el-button
        >
      </el-col>
    </el-row>
    <el-tree
      :id="'case' + activeName"
      :data="dataList"
      draggable
      :props="defaultProps"
      default-expand-all
      highlight-current
      node-key="id"
      ref="tree"
      :indent="32"
      :expand-on-click-node="false"
      :allow-drop="allowDrop"
      :allow-drag="allowDrag"
      @node-drop="handleDrop"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span style="width: 33%">{{ node.label }}</span>
        <span style="width: 33%">{{ data.final_name }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="() => handleAdd(data)"
          >
          </el-button>
          <el-button
            type="success"
            size="mini"
            icon="el-icon-edit"
            @click="() => handleEdit(node, data)"
          >
          </el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="() => handleDelete(node, data)"
          >
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="600px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="案件配置项" prop="name">
          <el-input v-model="form.name" placeholder="案件配置项" clearable />
        </el-form-item>
        <el-form-item label="父项" prop="parent">
          <el-cascader
            ref="parentRef"
            v-model="selectedKeys"
            :options="dataList"
            :props="props"
            @change="handleChange"
            clearable
          ></el-cascader>
          <!-- <el-select v-model="form.parent" placeholder="配置父项" clearable>
            <el-option
              v-for="item in parents"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="案件终结标志" prop="is_final">
          <el-switch v-model="form.is_final"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="handleSave"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getParentsPath } from "@/utils/index";
import {
  getProgressList,
  addProgress,
  updateProgress,
  delProgress,
  updateBatchProgress,
  getParentProgressList,
} from "@/api/case";
const defaultForm = {
  id: null,
  name: "",
  parent: null,
  is_final: false,
  case_type: null,
  sort: null,
};

export default {
  name: "Phase",
  props: {
    activeName: {
      required: true,
      type: Number,
    },
    listLoading: {
      required: true,
      type: Boolean,
      default() {
        return true;
      },
    },
    dataList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        name: [{ required: true, message: "请输入配置项", trigger: "blur" }],
      },
      title: "案件进度配置",
      warning_title: "进度配置：可上下拖拉重新排序",
      dialogVisible: false,
      parents: [],
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true,
      },
      selectedKeys: [],
      dialogType: "new",
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  computed: {
    getTitle() {
      return this.dialogType === "edit"
        ? `编辑${this.title}`
        : `新增${this.title}`;
    },
  },
  mounted() {
    // this.rowDrop();
    // this.getParentProgress();
  },
  methods: {
    getParentProgress() {
      const params = {
        case_type: this.activeName,
      };
      getParentProgressList(params)
        .then((res) => {
          this.parents = res;
        })
        .catch((error) => {
          this.$message.error("获取父项失败");
        });
    },
    handleAdd(data) {
      console.log(data);
      this.form = Object.assign({}, defaultForm);

      this.selectedKeys = [];
      let children = null;
      if (data) {
        this.form.parent = data.id;
        children = data.children || [];
      } else {
        children = this.dataList;
      }

      let max = 0;

      if (children.length > 0) {
        const sorts = children.map((item) => {
          return item.sort;
        });
        console.log(sorts);
        max = Math.max.apply(null, sorts);
      }
      console.log(max);
      this.form.sort = max + 1;
      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        if (data) {
          this.selectedKeys = getParentsPath(this.form.parent, this.dataList);
        }
        this.$refs.formRef.clearValidate();
      });
    },
    handleEdit(node, data) {
      this.form = Object.assign({}, data);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.selectedKeys = getParentsPath(this.form.parent, this.dataList);
        this.$refs.formRef.clearValidate();
      });
    },
    handleDelete(node, data) {
      this.$confirm("确定要删除该信息吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const parent = node.parent;
          console.log(parent);
          const children = parent.data.children || parent.data;
          const index = children.findIndex((d) => d.id === data.id);
          children.splice(index, 1);

          const res = await delProgress(data.id);
          this.$emit("progress", { case_type: this.activeName });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async handleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";

        let res = null;

        if (isEdit) {
          res = await updateProgress(this.form);
        } else {
          this.form.case_type = +this.activeName;
          res = await addProgress(this.form);
        }

        const { id } = res;
        if (id > 0) {
          this.$emit("progress", { case_type: this.activeName });
          this.getParentProgress();
        }

        const { name } = this.form;
        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>进度配置: ${name}</div>
            `,
          type: "success",
        });
      });
    },
    //排序
    updateSorts(parent_id, children) {
      const updateData = children.map((item, index) => {
        item.sort = index + 1;
        return { id: item.id, sort: item.sort, parent: parent_id || null };
      });
      console.log(updateData);
      const data = {
        update_ids: updateData,
      };
      updateBatchProgress(data)
        .then((res) => {
          this.$message.success("排序成功");
        })
        .catch((error) => {
          this.$message.error("排序失败!" + error.response.data.message);
          // console.log(error);
        });
    },

    handleChange(value) {
      console.log(value, this.$refs.parentRef.getCheckedNodes());
      if (this.selectedKeys.length > 0) {
        this.form.parent = this.selectedKeys[this.selectedKeys.length - 1];
      } else {
        this.form = null;
      }
    },
    handleProgress() {
      this.$emit("progress", { case_type: this.activeName });
    },

    remove(node, data) {
      console.log(node, data);
      const parent = node.parent;
      console.log(parent);
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
    },
    allowDrop(draggingNode, dropNode, type) {
      if (dropNode.level === 1 || dropNode.level === 2) {
        return true;
      } else {
        return type !== "inner";
      }
    },
    allowDrag(draggingNode) {
      return draggingNode.level <= 3;
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log(dropNode, dropType);
      if (dropType == "inner") {
        const parent_id = dropNode.data.id;
        const children = dropNode.data.children;
        this.updateSorts(parent_id, children);
      } else {
        if (dropNode.level === 1) {
          draggingNode.data.parent = dropNode.data.id;
        } else {
          draggingNode.data.parent = dropNode.data.parent;
        }
        const parent = dropNode.parent;
        const parent_id = parent.data.id;
        const children = parent.data.children || parent.data;
        this.updateSorts(parent_id, children);
      }
      // console.log(this.dataList);
    },
  },
};
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 10px;
}
</style>
